<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cancel</title>
</head>
<body>
    <button onclick="test1()">请求1</button>
    <button onclick="test2()">请求2</button>
    <button onclick="cancelReq()">取消请求</button><br/>
    <div id="result"></div>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.20.0/axios.js"></script>
    <script>
        const resutl = document.getElementById('result');
        axios.defaults.baseURL = 'http://localhost:9002'

        let cancel =null;

        function test1(params){
            axios({
                url:'/products1',
                cancelToken: new axios.CancelToken(c =>{
                    cancel = c;
                })

            }).then(response => {
                console.log('请求成功', response);
                resutl.innerText = JSON.stringify(response.data);
            },
            error => {
                cancel = null;
                console.log('请求失败', error.message, error);
                resutl.innerText = error.message;
            });
        }


        function test2(params){
            axios({
                    url:'/products2'
                }
            ).then(response => {
                console.log('请求成功', response);
                resutl.innerText = JSON.stringify(response.data);
            },
            error => {
                cancel = null;
                console.log('请求失败', error.message, error);
                resutl.innerText = error.message;
            });
        }


        function cancelReq(){
            if(typeof cancel === 'function'){
                cancel('用户取消请求。')
            } else {
                console.log('没有可取消的请求');
            }
        }
    </script>

</body>
</html>